package com.pay.common.utils;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pay.common.enums.PayWayEnum;
import com.pay.common.resp.PayNotifyData;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;

public class PayDigestUtil {


    /**
     *
     * a b c
     *
     * acb
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, Object> data, String key, String signType) throws Exception {

        //获取key的集合
        Set<String> keySet = data.keySet();

        //定义string数组
        String[] keyArray = keySet.toArray(new String[keySet.size()]);

        //对数组进行排序
        Arrays.sort(keyArray);


        //拼接字符串 k=v&k1=v1
        StringBuilder sb = new StringBuilder();


        for (String k : keyArray) {

            if (k.equals("sign")) {
                continue;
            }

            if (k.equals("signType")) {
                continue;
            }

            String keyStr = data.get(k) == null?"": data.get(k).toString();


            // 参数值为空，则不参与签名
            if (keyStr.trim().length() > 0){
                sb.append(k).append("=").append(data.get(k).toString().trim()).append("&");
            }
        }

        //加上密钥
        sb.append("key=").append(key);


        if("MD5".equals(signType)){

            return MD5.create().digestHex(sb.toString()).toUpperCase();

        }
        return null;

    }

    public static void main(String[] args) {

        PayNotifyData payNotifyData = new PayNotifyData();

        payNotifyData.setMchId("1000");
        payNotifyData.setOrderId("test123");
        payNotifyData.setPayChannel("alipay");
        payNotifyData.setPayWay(PayWayEnum.ALIPAY_QRCODE_PAY.getCode());
        payNotifyData.setPasySerialNo("1234567");

        JSONObject jsonObject  = (JSONObject) JSON.toJSON(payNotifyData);


        try {
            String sign = PayDigestUtil.generateSignature(jsonObject,"test123","MD5");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
